<template>
  <div>
    <ListTab v-model="handleStatus" :show-header="!showMobilePage" :tabs="tabList" is-table @tabClick="handleTabClick" />
    <div class="customer">
      <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
        <dataDisplay
          ref="dataDisplayRef"
          :data-list="[
            {data: statisticsData.lastThreeDaysCount, label: '近三天过期', icon: incomeAmountIcon, isMoney: false },
            {data: statisticsData.lastMonthsCount, label: '近一个月过期', icon: costIcon, isMoney: false },
            {data: statisticsData.lastThreeMonthsCount, label: '近三个月过期', icon: rmb, isMoney: false },
            {data: statisticsData.expiredCount, label: '已过期合同', icon: icon_7, isMoney: false }
          ]"
          style="margin-bottom:16px;"
          @handleNumClick="handleNumClick"
        />
        <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
          <FilterInput
            v-model="filterInput"
            :filter-list="filterList"
            show-search-btn
            class="FilterTool"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @deleteTagBefore="deleteTagBefore"
            @filterTagStatus="filterTagStatus"/>
          <div class="opeator-bar">
            <el-button v-if="hasRouteAuth('crm:contractManage:add')" class="btn-right-item batch-set" style="margin-right: 12px;" size="small" @click="toCreate(10)">
              新建<i class="el-icon-plus el-icon--right"/>
            </el-button>
            <MoreOpeator
              v-if="hasRouteAuth(['crm:contractManage:import', 'crm:contractManage:batchExport'])"
              ref="btnGroupRef"
              :list="moreOperatorList"
            />
          </div>
        </div>
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length > 0"
            ref="legalTableRef"
            :data="list.items"
            :row-class-name="tableRowClassName"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            header-cell-class-name="order-data-header-cell"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              align="center"
              type="selection"
              fixed="left"
              width="50"
            />
            <u-table-column align="left" label="流程编码" min-width="200">
              <template slot-scope="scope">
                <ToolTip :is-can-click="!!scope.row.flowCode" :content="scope.row.flowCode" @handelClick="toDetail(scope)" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="项目名称" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.contractName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="合同编号" min-width="130" prop="contractCode" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.contractCode" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="待审批角色" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.reviewRole" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="待审批人员" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.pendApproval" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="法务审批人" min-width="135">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.legalApprover" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="审批进度" min-width="120">
              <template slot-scope="scope">
                <el-progress
                  v-if="handelProgess(scope.row.reviewProgress) || handelProgess(scope.row.reviewProgress) === 0"
                  :percentage="handelProgess(scope.row.reviewProgress)"
                  :stroke-width="10"
                  :format="() => scope.row.reviewProgress"
                  :color="`${handelProgess(scope.row.reviewProgress) === 100 ? '#31CC9C' : '#406eff'}`"
                  class="progress-cell" />
                <el-tooltip v-else-if="scope.row.reviewProgress" :open-delay="800" placement="top-start" effect="dark">
                  <div slot="content" style="max-width:200px;"> {{ scope.row.reviewProgress }}</div>
                  <div class="ellipsis">{{ scope.row.reviewProgress }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="审批时间" min-width="150" prop="lastAuditTime" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.lastAuditTime/1000 | standardFormatNoHour('YYYY/MM/DD HH:mm', '--') }}
              </template>
            </u-table-column>
            <u-table-column align="left" label="合同类型" min-width="155">
              <template slot-scope="scope">
                {{ scope.row.contractType | contractType }}
              </template>
            </u-table-column>
            <u-table-column align="left" label="合同回收" min-width="120">
              <template slot-scope="scope">
                <span v-if="canScanFileUpload(scope)" class="contract-recycle" @click="contractRecycle(scope)">
                  {{ scope.row.recycleAttachmentNum || '上传' }}
                  <span v-if="scope.row.recycleAttachmentNum"> 个</span>
                </span>
                <span v-else class="contract-recycle disable">
                  {{ scope.row.recycleAttachmentNum || '上传' }}
                  <span v-if="scope.row.recycleAttachmentNum"> 个</span>
                </span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人（职位）" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="`${scope.row.creator || '--'}${scope.row.creatorPost ? '（' + scope.row.creatorPost + '）' : ''}`" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人（职位）" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="`${scope.row.proposer || '--'}${scope.row.post ? '（' + scope.row.post + '）' : ''}`" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="签约对方" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.oppCompany" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="我方签约主体" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.subject"/>
              </template>
            </u-table-column>
            <u-table-column align="left" label="合作方式" width="100">
              <template slot-scope="scope">
                {{ scope.row.contractDate | mapOptions(options.dateTypeOptions) }}
              </template>
            </u-table-column>
            <u-table-column align="left" label="合同日期" width="210" prop="contractEffectEndDate" sortable="custom">
              <template slot-scope="scope">
                <el-tooltip :open-delay="showMobilePage ? 100 : 800" placement="top" effect="dark">
                  <div slot="content" style="max-width: 220px; white-space: nowrap; padding: 0 10px;">
                    <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null || scope.row.contractType === 10">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} - {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                    <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                  </div>
                  <div class="ellipsisOne">
                    <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null || scope.row.contractType === 10">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} - {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                    <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                  </div>
                </el-tooltip>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人部门" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.department"/>
              </template>
            </u-table-column>
            <u-table-column align="left" label="来源" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.sourceType === 1 ? '审批' : '创建' }}
              </template>
            </u-table-column>
            <u-table-column align="left" label="归档编号" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.archiveCode"/>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="150" prop="createTime" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.createTime/1000 | standardFormatNoHour('YYYY/MM/DD HH:mm', '--') }}
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" align="left" label="操作" fixed="right">
              <template slot-scope="scope">
                <div class="flex-center">
                  <div v-if="!showMobilePage && showViewBtn(scope.row)" class="button-text" @click.stop="toDetail(scope)">查看</div>
                  <MoreOpeator
                    v-if="showEditBtn(scope.row) || showDeleteBtn(scope.row) || showChangeBtn(scope.row) || (showMobilePage && showViewBtn(scope.row))"
                    :list="[
                      {
                        label: '查看',
                        handelClick: () => {toDetail(scope)},
                        auth: showMobilePage && showViewBtn(scope.row)
                      },{
                        label: '编辑',
                        handelClick: () => {toEdit(scope)},
                        auth: showEditBtn(scope.row)
                      },{
                        label: '删除',
                        handelClick: () => {toDelete(scope)},
                        auth: showDeleteBtn(scope.row)
                      },{
                        label: '转交',
                        handelClick: () => {handleSingleApproverChange(scope.row.id)},
                        auth: showChangeBtn(scope.row)
                      }
                  ]">
                    <div v-if="!showMobilePage" slot="button" :class="{'bl': showViewBtn(scope.row)}" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
          <el-row v-if="showMobilePage" type="flex" justify="left">
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :small="true"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="pageLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
          <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
            <template v-if="showMobilePage">
              <FilterInput
                v-model="filterInput"
                :filter-list="filterList"
                show-mobile-icon
                show-search-btn
                class="FilterTool"
                @handelClick="queryClick"
                @queryEmpty="queryEmpty"
                @filterTagStatus="filterTagStatus" />
              <MoreOpeator
                v-if="hasRouteAuth(['crm:contractManage:import', 'crm:contractManage:batchExport'])"
                ref="btnGroupRef"
                :list="moreOperatorList"
                show-mobile-icon
              />
              <CreateBtn
                v-if="hasRouteAuth('crm:contractManage:add')"
                mobile-table
                style="width: 100%"
                @click.native="toCreate(10)"/>
            </template>
            <template v-else>
              <span style="flex:1;"/>
              <el-pagination
                :current-page="list.page"
                :page-size="list.perPage"
                :total="list.total"
                :page-sizes="[20, 50, 100, 250, 500]"
                layout="total, prev, pager, next, sizes, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </template>
          </fixed-pagination>
        </div>
      </div>
    </div>
    <ContractRecycleDialog ref="contractRecycleDialog" @success="recycleSuccess" />
    <ApproverChange ref="approverChangeDialog" :business-type="BUSINESS_TYPE.CONTRACT" :ids="curSelectedId" @changeCallBack="changeCallBack"/>
  </div>
</template>

<script>
// 组件
import createButton from '@/components/CreateButton';
import ImportButton from '@/components/ImportButton';
import ExportButton from '@/components/ExportButton';
import Title from '@/components/Title';
import ListTab from '@/components/ListTab';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import ContractRecycleDialog from '@/components/contractRecycle/contractRecycleDialog';
import ApproverChange from '@/components/Common/auditProcess/approverChange';
import upAttachment from '@/components/Common/upAttachment/index';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import CreateBtn from '@/components/Common/baseComponent/createBtn';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
// api
import { getManageList, deleteContract, getContractManageListTabs, getManageStatistics } from '@/api/legal';
import { getDepartmentAll } from '@/api/config';
import { getIssueOurTitleList } from '@/api/issueInvoice';
// filter
import { contractType } from '@/filters/status';
import { mapOptions } from '@/filters';
import { standardFormatNoHour } from '@/filters/date';
import options from './module/options';
// mixins
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import approverChange from '@/mixins/approverChange';
import mobileTable from '@/mixins/mobileTable';
// utils
import { hasRouteAuth } from '@/utils/permission';
import { BUSINESS_TYPE } from '@/utils/const/process';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
import { handelProgess } from '@/utils/process';
// img
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import costIcon from '@/assets/dataDisplay/icon_45.png';
import rmb from '@/assets/dataDisplay/rmb.png';
import icon_7 from '@/assets/dataDisplay/icon_7.png';

export default {
  name: 'ContractManagement',
  filters: {
    standardFormatNoHour,
    contractType,
    mapOptions
  },
  components: {
    createButton,
    ImportButton,
    ExportButton,
    Title,
    ListTab,
    EmptyPlaceholder,
    upAttachment,
    MoreOpeator,
    ContractRecycleDialog,
    ApproverChange,
    CreateBtn,
    dataDisplay
  },
  mixins: [tableSelections, TableAdaptive, approverChange, mobileTable],
  data() {
    return {
      BUSINESS_TYPE,
      incomeAmountIcon,
      costIcon,
      rmb,
      icon_7,
      sortType: '',
      sortName: '',
      tabList: [],
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      listLoading: true,
      handleStatus: -1,
      options,
      filterInput: {},
      deptTreeList: [],
      curSelectedId: '', // 请求变更操作的合同id
      mediumBtnStyle: {
        fontSize: '12px',
        width: '100%',
        whiteSpace: 'nowrap',
        padding: '0',
        marginLeft: '0px',
        marginRight: '0px',
        height: '30px',
        lineHeight: '30px',
        border: 'none',
        borderRadius: '0'
      },
      ids: '',
      tableRefName: 'legalTableRef',
      idKey: 'id',
      rangeKeyArr: [{
        attr: 'contractEffectStartDate',
        start: 'contractEffectStartDateStart',
        end: 'contractEffectStartDateEnd',
        type: 'time',
        addTime: true
      }, {
        attr: 'contractEffectEndDate',
        start: 'contractEffectEndDateStart',
        end: 'contractEffectEndDateEnd',
        type: 'time',
        addTime: true
      }, {
        attr: 'contractAmount',
        start: 'contractAmountMin',
        end: 'contractAmountMax',
        type: 'moneyFixedTwo'
      }],
      arrayKeyArr: ['departmentIdList'],
      isUmyTable: true,
      subjectOptions: [],
      statisticsData: {
        lastThreeDaysCount: null,
        lastMonthsCount: null,
        lastThreeMonthsCount: null,
        expiredCount: null
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      return [
        { keyword: 'contractName', name: '项目名称', type: 'input', labelWidth: '99px' },
        { keyword: 'contractCode', name: '合同编号', type: 'input', labelWidth: '99px' },
        { keyword: 'flowCode', name: '流程编码', type: 'input', labelWidth: '99px' },
        { keyword: 'pendApproval', name: '待审批人员', type: 'input', labelWidth: '99px' },
        { keyword: 'approver', name: '审批人', type: 'input', labelWidth: '99px' },
        { keyword: 'proposer', name: '申请人', type: 'input', labelWidth: '99px' },
        // { keyword: 'waitApprover', name: '待审批角色', type: 'input', labelWidth: '99px' },
        { keyword: 'oppCompany', name: '签约对方', type: 'input', labelWidth: '99px' },
        { keyword: 'archiveCode', name: '归档编号', type: 'input', labelWidth: '99px' },
        { keyword: 'contractAmount', name: '合同金额', labelWidth: '99px', type: 'inputRange', isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'contractType', name: '合同类型', type: 'select', options: [...options.typeOptions, {
          value: 10,
          label: '历史合同'
        }] },
        { keyword: 'tempSource', name: '合同模板来源', type: 'select', options: [...options.tempSourceOptions, { value: 4, label: '新拟定' }], placeholder: '模板来源' },
        { keyword: 'contractSubject', name: '我方签约主体', type: 'select', options: this.subjectOptions, placeholder: '签约主体' },
        { keyword: 'contractWay', name: '合作方式', type: 'select', options: [...options.dateTypeOptions] },
        { keyword: 'departmentIdList', name: '申请人部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'contractEffectStartDate', name: '合同起始日期', type: 'rangeDate', timeType: 'daterange', labelWidth: '99px', addQuickOptions: [30, 90] },
        { keyword: 'contractEffectEndDate', name: '合同结束日期', type: 'rangeDate', timeType: 'daterange', labelWidth: '99px', addQuickOptions: [30, 90] },
        { keyword: 'process', name: '审批状态', type: 'select', options: [...options.auditOptions] },
        {
          keyword: 'waitApprover',
          name: '待审批角色',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { needNumber: 1 },
          labelName: 'name',
          placeholder: '待审批角色',
          searchkeyword: 'keyword',
          apiUrl: 'admin/contract/pendApproval/list' },
        { keyword: 'rebates', name: '销售折扣/返利', type: 'select', options: [{ value: 1, label: '有' }, { value: 0, label: '无' }] }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 256 : 246;
    },
    moreOperatorList() {
      return [
        {
          label: '批量上传',
          type: 'import',
          callback: this.importCallback,
          importApi: '/admin/contractManage/importHistory',
          auth: hasRouteAuth('crm:contractManage:import')
        },
        {
          label: '批量导出',
          type: 'export',
          exportApi: '/admin/contractManage/list/batchExport',
          exportName: '合同管理列表',
          isBeforeExport: true,
          beforeExport: this.handleBatchExport,
          refName: 'batchExportRef',
          auth: hasRouteAuth('crm:contractManage:batchExport')
        },
        {
          label: '批量转交',
          handelClick: () => this.handleBatchApproverChange(this.BUSINESS_TYPE.CONTRACT)
        }
      ];
    }
  },
  activated() {
    if (this.$route.meta.handleStatus) {
      this.handleStatus = this.$route.meta.handleStatus;
    }
    const { isChange } = this.$route.meta;
    this.fetchData(!!isChange);
    this.queryDeptTreeList();
    this.getTabList();
    this.getSubJectOptions();
  },
  // created() {
  //   this.fetchData(true);
  //   this.getTabList();
  // },
  methods: {
    handelProgess,
    getSubJectOptions() {
      this.subjectOptions = [];
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.subjectOptions.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
        }
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    hasRouteAuth,
    canScanFileUpload(scope) {
      const processStatus = scope.row.process;
      const setEvents = scope.row.setEvents;
      if (scope.row.contractType === 10) {
        return false;
      }
      if (processStatus === 1) {
        if (setEvents && setEvents.includes(1) && this.hasRouteAuth('crm:contract:scanFileUpload')) {
          return true;
        } else {
          return false;
        }
      } else if (processStatus === 4) {
        if (this.hasRouteAuth('crm:contract:scanFileUpload') && this.hasRouteAuth('crm:contract:scanFileDownload')) {
          return true;
        } else {
          return false;
        }
      }
      return false;
    },
    handleTabClick(id) {
      this.handleStatus = id;
      this.queryClick();
    },
    handleNumClick(index) {
      // 0近三天 1近一个月 2近三个月 3已过期
      const unit = 24 * 60 * 60 * 1000;
      const today = new Date(new Date().toLocaleDateString()).getTime() / 1000;
      const endDate = [
        Math.round((new Date(new Date().toLocaleDateString()).getTime() + 2 * unit) / 1000),
        Math.round((new Date(new Date().toLocaleDateString()).getTime() + 29 * unit) / 1000),
        Math.round((new Date(new Date().toLocaleDateString()).getTime() + 89 * unit) / 1000),
        Math.round((new Date(new Date().toLocaleDateString()).getTime() - unit) / 1000)
      ];
      if (index === 3) {
        this.$set(this.filterInput, 'contractEffectEndDate', [null, endDate[index] * 1000]);
      } else {
        this.$set(this.filterInput, 'contractEffectEndDate', [today * 1000, endDate[index] * 1000]);
      }
      this.fetchData();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      this.filterInput = {};
      this.queryClick();
    },
    deleteTagBefore(key) {
      if (key === 'contractEffectStartDate') {
        delete this.filterInput.contractEffectStartDate;
      }
      if (key === 'contractEffectEndDate') {
        delete this.filterInput.contractEffectEndDate;
      }
    },
    importCallback() {
      this.fetchData(true);
    },
    // 多选
    tableSelectionChange(e) {
      this.selectList = e;
      this.ids = e.map(item => item.id).join(',');
    },
    // 批量导出
    handleBatchExport() {
      const params = this.formatParams();
      this.ids && (params.ids = this.ids);
      this.$refs['btnGroupRef'].btnExport(params, 'batchExportRef');
    },
    // 是否展示查看
    showViewBtn(data) {
      return hasRouteAuth('crm:contractManage:read') && data.process !== 0;
    },
    // 是否展示编辑
    showEditBtn(data) {
      return hasRouteAuth('crm:contractManage:edit') && (data.process === 0 || data.sourceType === 2);
    },
    // 是否展示删除
    showDeleteBtn(data) {
      return hasRouteAuth('crm:contractManage:delete') && (data.process === 0 || data.sourceType === 2);
    },
    // 是否展示审批人变更
    showChangeBtn(data) {
      return hasRouteAuth('crm:contract:approverChange') && ![0, 4].includes(data.process);
    },
    // 审批人员单个合同变更
    handleSingleApproverChange(id) {
      if (!id) {
        this.$message.warning('合同ID无效');
        return;
      }
      this.curSelectedId = id + '';
      this.$refs['approverChangeDialog'].dialogVisible = true;
    },
    async getTabList() {
      try {
        const result = await getContractManageListTabs();
        if (result.code === 200) {
          // result.data.unshift({ name: '全部', id: -1 });
          this.tabList = result.data;
          // this.handleStatus = result.data[0].id;
        }
      } catch (error) {
        this.tabList = [
          { id: -1, name: '全部', num: 0 },
          { id: 0, name: '执行中', num: 0 },
          { id: 1, name: '已完成', num: 0 }
        ];
        console.log(error);
      }
    },
    // 表格tab切换按钮
    statusTabChange(status) {
      this.handleStatus = status;
      this.queryClick();
    },
    contractRecycle(scope) {
      this.$refs['contractRecycleDialog'].dialogVisible = true;
      const data = {
        id: scope.row.id,
        attachment: scope.row.recycleAttachment || [],
        isReview: scope.row.process === 4 && hasRouteAuth('crm:contract:scanFileDownload') || (scope.row.process === 1 && hasRouteAuth('crm:contract:scanFileDownload') && scope.row.setEvents && scope.row.setEvents.includes(1))
      };
      this.$refs['contractRecycleDialog'].initInfo(data);
    },
    recycleSuccess() {
      this.fetchData();
    },
    getManageStatistics(params) {
      getManageStatistics(params).then(res => {
        if (res.code === 200) {
          this.statisticsData = res.data;
        }
      }).catch(err => console.error(err.message));
    },
    fetchData(reset = false) {
      try {
        if (reset) this.list.page = 1;
        this.listLoading = true;
        const params = this.formatParams();
        this.getManageStatistics(params);
        getManageList(params).then(({ data }) => {
          this.list = data;
          this.listLoading = false;
          this.list.isInit = false;
          if (this.setSelectRow) this.setSelectRow(data.items);
        }, result => {
          this.listLoading = false;
          this.list.isInit = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.filterInput));
      params.page = this.list.page;
      params.perPage = this.list.perPage;
      params.handleStatus = this.handleStatus;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      /* if (params.contractEffectDate && params.contractEffectDate.length === 2) {
        params.contractEffectStartDate = Math.round(params.contractEffectDate[0]);
        params.contractEffectEndDate = Math.round(params.contractEffectDate[1]);
      }
      delete params.contractEffectDate; */
      if (params.waitApprover && params.waitApprover.length) {
        params.waitApprover = `,${params.waitApprover.join(',')},`;
      }
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      return params;
    },
    rowClick(row, column, event) {
      if (row.process === 0) {
        this.$router.push({
          name: 'hisEditContract',
          params: {
            id: row.id
          }
        });
      } else {
        this.$router.push({
          name: 'hisContractDetail',
          params: {
            id: row.id
          },
          query: {
            processId: row.processId
          }
        });
      }
    },
    toEdit(scope) {
      this.$router.push({
        name: 'hisEditContract',
        params: {
          id: scope.row.id
        }
      });
    },
    toCreate(type) {
      this.$router.push({
        name: 'hisCreateContract',
        query: {
          type
        }
      });
    },
    toDetail(scope) {
      if (scope.row.contractType === 10) {
        this.$router.push({
          name: 'hisContractDetail',
          params: {
            id: scope.row.id
          },
          query: {
            processId: scope.row.processId,
            isFromManageIndex: 1
          }
        });
      } else {
        const routeUrl = this.$router.resolve({
          name: 'contractDetail',
          params: {
            id: scope.row.id
          },
          query: {
            processId: scope.row.processId,
            isFromManageIndex: 1
          }
        });
        window.open(routeUrl.href, '_blank');
      }
    },
    async toDelete(scope) {
      this.$confirm('确定删除该合同？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        deleteContract(scope.row.id).then(res => {
          this.$message.success('删除成功');
          if (this.list.items && this.list.items.length > 1) {
            this.fetchData();
          } else if (this.list.items.length === 1) {
            this.fetchData(true);
          }
        }, result => {
          // this.$message.error(result.message);
        }).catch(err => {
          console.error(err);
        });
      });
    },
    handleSizeChange(val) {
      this.list.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.list.page = toPage;
      this.fetchData();
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.contract-recycle {
  cursor: pointer;
  color: #406EFF;
  font-weight: bold;
  &.disable {
    cursor: not-allowed;
    color: #999999;
  }
}
.batch-set {
  display: flex;
  align-items: center;
  padding: 0 12px;
  font-size: 14px;
  background: #406eff;
  border-color: #406eff;
  color: #fff;
  height: 32px;
}

.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.customer {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .el-row {
      padding: 0;
    }
  }
  &::v-deep {
    .num {
      cursor: pointer;
    }
  }
}
</style>
